const { db } = require('../config')
const { command } = require('../config')
const { workorder_collection } = require('../config')
const _ = command
const pick = require('lodash/pick')
exports.main = async (event, context) => {
  const data = event;
  // 根据筛选条件查询工单
  var filter = {};
  const userInfo = event.userInfo;
  if (data.queryType && data.queryType == "todoworkorder") {
    filter.currentProcess = new RegExp(`${userInfo.position}(发起|审批)`, 'i');
  }
  if (data.hasOwnProperty('status') && data.status != '') {
    filter.status = new RegExp(data.status, "i");
  } else {
    filter.status = _.neq('已删除');
  }
  if (data.hasOwnProperty('createDateTime') && data.createDateTime != '') filter.createDateTime = new RegExp(data.createDateTime, "i");
  if (data.hasOwnProperty('region') && data.region != '') filter.region = new RegExp(data.region, "i");
  if (data.hasOwnProperty('grid') && data.grid != '') filter.grid = new RegExp(data.grid, "i");
  if (data.hasOwnProperty('creator') && data.creator != '') filter.creator = new RegExp(data.creator, 'i')
  if (data.hasOwnProperty('creatorAccount') && data.creatorAccount != '') filter.creatorAccount = new RegExp(data.creatorAccount, 'i')
  if (data.hasOwnProperty('currentProcess') && data.currentProcess != '') filter.currentProcess = new RegExp(data.currentProcess, 'i')
  if (data.hasOwnProperty('currentPosition') && data.currentPosition != '') filter.currentPosition = new RegExp(data.currentPosition, 'i')
  if (data.hasOwnProperty('obdAndStaff') && data.obdAndStaff != '') filter.obdAndStaff = new RegExp(data.obdAndStaff, 'i')
  if (data.hasOwnProperty('type') && data.type != '') filter.type = new RegExp(data.type, "i");
  const countRs = await db.collection(workorder_collection)
    .where(filter)
    .count();
  page = data.page;
  pageSize = data.pageSize;
  console.log('查询条件', filter)
  const lists = await db.collection(workorder_collection)
    .where(filter)
    .orderBy('createDateTime', 'desc')
    .skip(page * pageSize)
    .limit(pageSize)
    .get();
  var woList = [];
  if (lists.data && lists.data.length) {
    woList = lists.data.map(i => {
      const item = pick(i, ['_id', 'log', 'creator', 'createDateTime', 'currentProcess', 'status', 'grid']);
      // 解析 obdAndStaff 字符串为对象数组
      const obdAndStaff = JSON.parse(i.obdAndStaff);

      // 提取所有对象中的 newStaffName 值，并使用 Set 来去除重复值
      const newStaffNamesSet = new Set(obdAndStaff.map(obj => obj.newStaffName));

      // 将 newStaffNamesSet 转换成数组并添加到 item 中
      item.newStaffNames = Array.from(newStaffNamesSet);
      return item;
    })
  }
  // console.log('查询结果', woList.obdAndStaff)
  // 
  return { data: woList, page, pageSize, total: countRs.total };
}
